import { Injectable } from '@nestjs/common'
import { CreateAwardRuleDto } from './dto/create-award-rule.dto'
import { UpdateAwardRuleDto } from './dto/update-award-rule.dto'
import { Equal, Repository, Not, IsNull } from 'typeorm'
import { InjectRepository } from '@nestjs/typeorm'
import { AwardRule } from './entities/award-rule.entity'
import { AwardRuleTypeEnum } from 'src/types/awardRule'
import { formatOptionData } from 'src/utils'
@Injectable()
export class AwardRuleService {
  constructor(
    @InjectRepository(AwardRule)
    private readonly awardRule: Repository<AwardRule>
  ) {}
  create(createAwardRuleDto: CreateAwardRuleDto) {
    const awardRule = new AwardRule()
    awardRule.name = createAwardRuleDto.name
    awardRule.score = createAwardRuleDto.score
    awardRule.type = createAwardRuleDto.type
    awardRule.desc = createAwardRuleDto.desc
    return this.awardRule.save(awardRule)
  }

  /*
    FIXED: params.type为1时，查出来的数据是0的数据。为0时，查的是空数组。在数据库中使用sql语句查询也是一样的。
    经查验：数据为number时，错误。为string时，正确。
  */
  async findAll(params: {
    page: number
    pageSize: number
    type?: string
    isDelete?: boolean
  }) {
    const where = {}
    AwardRuleTypeEnum[params.type] && (where['type'] = Equal(params.type))
    params.isDelete && (where['deleteDate'] = Not(IsNull()))
    const data = await this.awardRule.find({
      where: { ...where },
      withDeleted: params.isDelete,
      skip: (params.page - 1) * params.pageSize,
      take: params.pageSize
    })
    const total = await this.awardRule.count({
      where: { ...where },
      withDeleted: params.isDelete
    })
    return { data, total }
  }

  async findAllOption() {
    const data = await this.awardRule.find()
    return formatOptionData(data)
  }

  async findOne(id: number) {
    return await this.awardRule.find({ where: { id: Equal(id) } })
  }

  update(id: number, updateAwardRuleDto: UpdateAwardRuleDto) {
    return this.awardRule.update(id, updateAwardRuleDto)
  }

  remove(ids: number[]) {
    return this.awardRule.softDelete(ids)
  }

  thoroughRemove(ids: number[]) {
    return this.awardRule.delete(ids)
  }

  restore(ids: number[]) {
    return this.awardRule.restore(ids)
  }
}
